﻿using Microsoft.SharePoint.Administration;
using SPSDeploy.Extensions.Controllers;
using SPSDeploy.Extensions.Extensions;
using System.Linq;
using System.Xml.Linq;

namespace SPSDeploy.Extensions.Modules.Compare
{
    /// <summary>
    /// Service application proxy compare module
    /// </summary>
    internal class ServiceApplicationProxyModule : BaseModule
    {

        /// <summary>
        /// Initialization
        /// </summary>
        /// <param name="controller"></param>
        internal ServiceApplicationProxyModule(BaseController controller)
            : base(controller)
        {
        }

        /// <summary>
        /// Execute module
        /// </summary>
        /// <param name="compare"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        internal override XElement Execute(XElement compare, XElement parent)
        {
            SPFarm farm = SPFarm.Local;
            XElement result = new XElement("serviceApplicationProxies");
            XElement adds = GetAddsElement();
            XElement deletes = GetDeletesElement();
            XElement element;
            foreach (SPServiceProxy serviceProxy in farm.ServiceProxies)
                foreach (SPServiceApplicationProxy applicationProxy in serviceProxy.ApplicationProxies)
                    if (ServiceApplicationProxyExtension.IncludeProxy(farm, applicationProxy))
                        if ((element = compare.Nodes().OfType<XElement>().Where(e => e.Attribute("name").Value == applicationProxy.DisplayName && e.Attribute("type").Value == applicationProxy.TypeName).FirstOrDefault()) == null)
                            deletes.Add(new XElement("serviceApplicationProxy", new XAttribute("name", applicationProxy.DisplayName), new XAttribute("type", applicationProxy.TypeName)));
            foreach (XElement application in compare.Nodes())
                if (!ServiceApplicationProxyExtension.ServiceApplicationProxyExists(farm.ServiceProxies, application.Attribute("name").Value, application.Attribute("type").Value))
                    adds.Add(new XElement("serviceApplicationProxy", new XAttribute("name", application.Attribute("name").Value), new XAttribute("type", application.Attribute("type").Value)));
            Tools.RollupElement(result, adds);
            Tools.RollupElement(result, deletes);
            controller.OnProgressMessage("Service application proxy information compared.");
            return result;
        }

    }
}